package Tables;

/*
 * SimpleTableDemo.java requires no other files.
 */
 
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import TableAdditions.CustomerTableAddition;
import TableAdditions.PersonelAddition;
import TableAdditions.main;
import TableEditions.PersonelEdition;
import Utility.Personnel;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class PersonelTableInterface extends JPanel{
    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    JButton personelAddButton=new JButton("Yeni");
    JButton personelDeleteButton=new JButton("Sil");
    JButton personelEditButton=new JButton("Düzenle");
    int selectedRow=-1;
    Personnel[] personels;
    
    
    final String[] newData=new String[9]; 					///////// for add new data to the table //only screen
    PersonelAddition additive;	
    PersonelEdition edit;	
    
    
    public PersonelTableInterface() {
    	
    	//super(new GridBagLayout());
 
        String[] columnNames = {
        						"Personel Adı",
                                "Telefon",
                                "Adres","Araç"};
 
	 	

        for(int i=0;i<columnNames.length;i++)
        	model.addColumn(columnNames[i]);	//add columns
        
       
        addNewItem();
       
        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);
      //Add the scroll pane to this panel.
        add(scrollPane);
        
        table.addMouseListener(new MouseAdapter() {
			
			
			@Override
			public void mouseClicked(MouseEvent arg0) {
				// TODO Auto-generated method stub
				 if (table.getColumnSelectionAllowed()
		                    && !table.getRowSelectionAllowed()) {
					  
		                System.out.println("11111111111111");
		                // Column selection is enabled
		                // Get the indices of the selected columns
		                int[] vColIndices = table.getSelectedColumns();
		            } else if (!table.getColumnSelectionAllowed()
		                    && table.getRowSelectionAllowed()) {
		            	// System.out.println("222222222222");
		            	 selectedRow=table.getSelectedRow(); 
		            	 
		            	 //System.out.println("selectedCustomer= "+customerNames[selectedRow]);
		                // Row selection is enabled
		                // Get the indices of the selected rows
		                int[] rowIndices = table.getSelectedRows();
		            } else if (table.getCellSelectionEnabled()) {
		                // Individual cell selection is enabled
		            	System.out.println("333333333333");

		                // In SINGLE_SELECTION mode, the selected cell can be retrieved using
		            	table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		                int rowIndex = table.getSelectedRow();
		                int colIndex = table.getSelectedColumn();
		              

		                // In the other modes, the set of selected cells can be retrieved using
		                table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		                table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

		                // Get the min and max ranges of selected cells
		                int rowIndexStart = table.getSelectedRow();
		                int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
		                int colIndexStart = table.getSelectedColumn();
		                int colIndexEnd = table.getColumnModel().getSelectionModel()
		                    .getMaxSelectionIndex();

		                // Check each cell in the range
		                for (int r=rowIndexStart; r<=rowIndexEnd; r++) {
		                    for (int c=colIndexStart; c<=colIndexEnd; c++) {
		                        if (table.isCellSelected(r, c)) {
		                        	System.out.println("4444444444444");
		                            // cell is selected
		                        }
		                    }
		                }
		            }
				
			}
		});
        
        
        
        personelAddButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				additive=new PersonelAddition(PersonelTableInterface.this);

				
			}
			
			
		});
        
        personelEditButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if(selectedRow>-1){
					edit=new PersonelEdition(PersonelTableInterface.this,personels[selectedRow]);
				}

				
			}
			
			
		});
        
        personelDeleteButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if(selectedRow!=-1){
					System.out.println("Delete special price");
					
					Connection con = null;
			        Statement st = null;
			        ResultSet rs = null;

			        String url = "jdbc:mysql://localhost:3306/mydb";
			        String user = "root";
			        String password = "qweasdzxc";
			        Object[][] mydata=null;
			        try {
			            con = (Connection) DriverManager.getConnection(url, user, password);
			            st = (Statement) con.createStatement();
			            st.executeUpdate("UPDATE  personel set activity='0',personel_vehicle_id='-1' WHERE personel_id='"+personels[selectedRow].getPersonnelId()+"'");
			            st.executeUpdate("UPDATE vehicle set vehicle_driver_id='-1',vehicle_availability='1' WHERE vehicle_driver_id='"+personels[selectedRow].getPersonnelId()+"'");
			            addNewItem();
			           
			            con.close();
			        } catch (SQLException ex) {
			            Logger lgr = Logger.getLogger(main.class.getName());
			            lgr.log(Level.SEVERE, ex.getMessage(), ex);

			        } finally {
			            try {
			                if (rs != null) {
			                    rs.close();
			                }
			                if (st != null) {
			                    st.close();
			                }
			                if (con != null) {
			                    con.close();
			                }

			            } catch (SQLException ex) {
			                Logger lgr = Logger.getLogger(main.class.getName());
			                lgr.log(Level.WARNING, ex.getMessage(), ex);
			            }
			        }
					/////////////////////////////////////////
				}
				
				

				
			}
			
			
		});
  
        addItem(personelAddButton,0,1,1,1,GridBagConstraints.CENTER);//call the addItem method and add in panel
        addItem(personelDeleteButton,1,1,1,1,GridBagConstraints.CENTER);//call the addItem method and add in panel
        addItem(personelEditButton,2,1,1,1,GridBagConstraints.CENTER);//call the addItem method and add in panel
        
        
       
       
    }
    
public static void main(String[] args) {
	new PersonelTableInterface().createAndShowGUI();
}
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    public void createAndShowGUI() {
        //Create and set up the window.
        JFrame myframe = new JFrame("Personel Tablosu");
        myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        //Create and set up the content pane.
        PersonelTableInterface newContentPane = new PersonelTableInterface();
        newContentPane.setOpaque(true); //content panes must be opaque
        myframe.setContentPane(newContentPane);
 
        //Display the window.
        TableGetXY tmp=new TableGetXY();
        myframe.setLocation(tmp.upperLeftX,tmp.upperLeftY);

        myframe.pack();
        myframe.setVisible(true);
    }

    /**
     *This method is good to use GridBagLayout simple
     * 
     */
    private void addItem(JComponent c, int x, int y, int width, int height, int align) {
        GridBagConstraints gc = new GridBagConstraints();
        gc.gridx = x;
        gc.gridy = y;
        gc.gridwidth = width;
        gc.gridheight = height;
        gc.weightx = 100.0;
        gc.weighty = 100.0;
        gc.insets = new Insets(5, 5, 5, 5);
        gc.anchor = align;
        gc.fill = GridBagConstraints.NONE;
        add(c, gc);
      }
    public void addNewItem(){
 		deleteAllRows(model);
 		
 		Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        String url = "jdbc:mysql://localhost:3306/mydb";			/////connection setups
        String user = "root";
        String password = "qweasdzxc";
        Object[][] mydata=null;
        int counter=0;
        try {
            con = (Connection) DriverManager.getConnection(url, user, password);		//create connections and setups
            st = (Statement) con.createStatement();
            rs=st.executeQuery("SELECT * from personel WHERE activity='1' ORDER BY personel_name");		//get query to the rs
            int i=0;
            while(rs.next())
            	++counter;
            if(counter!=0){
            rs.first();
            
            personels = new Personnel[counter];
            mydata=new Object[counter][5];
            personels[i]= new Personnel();
            personels[i].setPersonnelId(rs.getInt("personel_id"));
            mydata[i][0]=rs.getString("personel_name");	
            personels[i].setPersonnelName(rs.getString("personel_name"));
    		mydata[i][1]=rs.getString("personel_phone");
    		personels[i].setPersonnelPhone(rs.getString("personel_phone"));
    		mydata[i][2]=rs.getString("personel_address");
    		personels[i].setPersonnelAddress(rs.getString("personel_address"));
    		mydata[i][3]=rs.getString("personel_vehicle_id");
    		personels[i].setPersonnelVehicleId(rs.getInt("personel_vehicle_id"));
    		++i;
    		
            while(rs.next())								
            {
            	personels[i]= new Personnel();
                personels[i].setPersonnelId(rs.getInt("personel_id"));
                mydata[i][0]=rs.getString("personel_name");	
                personels[i].setPersonnelName(rs.getString("personel_name"));
         		mydata[i][1]=rs.getString("personel_phone");
         		personels[i].setPersonnelPhone(rs.getString("personel_phone"));
         		mydata[i][2]=rs.getString("personel_address");
         		personels[i].setPersonnelAddress(rs.getString("personel_address"));
         		mydata[i][3]=rs.getString("personel_vehicle_id");
         		personels[i].setPersonnelVehicleId(rs.getInt("personel_vehicle_id"));
         		++i;
        
            }
            /*for(int j=0;j<counter;j++){
            	rs=st.executeQuery("SELECT job_name from job WHERE job_id='"+mydata[j][3]+"'");
            	rs.next();
            	//mydata[j][3]=rs.getString("job_name");
            	
            }*/
            for(int j=0;j<counter;j++){
            	if(Integer.parseInt(mydata[j][3].toString())>0){
            	rs=st.executeQuery("SELECT vehicle_licence_plate from vehicle WHERE vehicle_id='"+mydata[j][3]+"'");
            	rs.next();
            	mydata[j][3]=rs.getString("vehicle_licence_plate");
            	}
            	else{
            		mydata[j][3]="Yok";
            	}
            	
            }
            
            table.setPreferredScrollableViewportSize(new Dimension(920, 600));
            table.setFillsViewportHeight(true);
            if(counter!=0)
            	for(int k=0;k<mydata.length;k++)
            		model.addRow(mydata[k]);
            
            }
            
            con.close();
            
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(main.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(main.class.getName());
                lgr.log(Level.WARNING, ex.getMessage(), ex);
            }
        }
	
  
    
 		
 		
     }
    
    public static void deleteAllRows(final DefaultTableModel model) {
	    for( int i = model.getRowCount() - 1; i >= 0; i-- ) {
	        model.removeRow(i);
	    }
	}
	
}


